layui.use([
  'laytpl',
  'jquery',
  'form',
  'layer'
], function () {
  const $ = layui.jquery
  const laytpl = layui.laytpl
  const form = layui.form
  const layer = layui.layer

  String.prototype.toFixed = function (d) {
    return Number(this).toFixed(d)
  }

  // 初始化
  laytpl($('#value').html()).render({
    buy   : {
      price: '0.00',
      taxes: '0.00',
      cost : '0.00'
    },
    sale  : {
      price : '0.00',
      taxes : '0.00',
      income: '0.00'
    },
    profit: '0.00'
  }, html => {
    $('.value-box .one').html(html)
    $('.value-box .all').html(html)
  })

  form.on('submit(calc)', function (e) {
    const field = e.field

    for (const key in field) {
      if (field.hasOwnProperty(key)) {
        if (field[key] === '') {
          layer.msg('请填写完整', { icon: 2 })
          return false
        }
      }
      else {
        layer.msg('未知错误', { icon: 2 })
        return false
      }
    }

    // 税率
    const tax = math.chain(field.tax_rate).divide(100).done().toFixed(4)

    // 单个买入
    const buy = {}
    buy.price = field.buy_price.toFixed(4)
    buy.taxes = math.chain(buy.price).multiply(tax).done().toFixed(4)
    buy.cost = math.chain(buy.price).add(buy.taxes).done().toFixed(2)

    // 全部买入
    const allBuy = {}
    allBuy.price = math.chain(buy.price).multiply(field.count).done().toFixed(4)
    allBuy.taxes = math.chain(allBuy.price).multiply(tax).done().toFixed(4)
    allBuy.cost = math.chain(allBuy.price).add(allBuy.taxes).done().toFixed(2)

    // 单次卖出
    const sale = {}
    sale.price = field.sale_price.toFixed(4)
    sale.taxes = math.chain(sale.price).multiply(tax).done().toFixed(4)
    sale.income = math.chain(sale.price).subtract(sale.taxes).done().toFixed(2)

    // 全部卖出
    const allSale = {}
    allSale.price = math.chain(sale.price).multiply(field.count).done().toFixed(4)
    allSale.taxes = math.chain(allSale.price).multiply(tax).done().toFixed(4)
    allSale.income = math.chain(allSale.price).subtract(allSale.taxes).done().toFixed(2)

    const one = {
      buy,
      sale,
      profit: math.chain(sale.income).subtract(buy.cost).done().toFixed(2)
    }
    const all = {
      buy   : allBuy,
      sale  : allSale,
      profit: math.chain(allSale.income).subtract(allBuy.cost).done().toFixed(2)
    }

    // 保留两位
    buy.price = buy.price.toFixed(2)
    buy.taxes = buy.taxes.toFixed(2)
    allBuy.price = allBuy.price.toFixed(2)
    allBuy.taxes = allBuy.taxes.toFixed(2)
    sale.price = sale.price.toFixed(2)
    sale.taxes = sale.taxes.toFixed(2)
    allSale.price = allSale.price.toFixed(2)
    allSale.taxes = allSale.taxes.toFixed(2)

    const tpl = $('#value').html()
    laytpl(tpl).render(one, html => {
      $('.value-box .one').html(html)
    })
    laytpl(tpl).render(all, html => {
      $('.value-box .all').html(html)
    })
  })
})